package com.gxgeek.order.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gxgeek.order.util.JsonUtil;
import com.gxgeek.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author gaoxing
 * @create 2018-03-29 上午11:57
 */
@Slf4j
@Component
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 水果
     * @param message
     */
    @RabbitListener(queuesToDeclare= @Queue("productInfo"))//监听并创建队列
    public void proessProductInfo(String message){

        List<ProductInfoOutput> productInfoOutput = JsonUtil.fromJson(message, new TypeReference<List<ProductInfoOutput>>(){});
        log.info("fruit MqReceiver:{}",productInfoOutput);

        //存储下redis
        for (ProductInfoOutput infoOutput : productInfoOutput) {
            redisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, infoOutput.getProductId()),
                    String.valueOf(infoOutput.getProductStock()));
        }
    }

}
